import {postJSON} from "./http";
import { apiBaseUrl } from "./config";
import DateUtils from "./DateUtils";
const app = getApp();
function setWxUserInfo(userInfo) {
  wx.setStorageSync('wxUserInfo', JSON.stringify(userInfo));
}

function getWxUserInfo() {
  let userInfo = wx.getStorageSync('wxUserInfo');
  return userInfo ? JSON.parse(userInfo) : null;
}

function getOpenId() {
  return wx.getStorageSync('openId');
}

//保存formId
function saveFormIds(formids) {
  if(formids.length > 0) {
    let param = { formids: formids };
    postJSON('/wxa/actformid/batchSave', param);
  }
}
//收集formId
function collectFormIds(e, formIdlist) {
  if (e.detail.formId != 'the formId is a mock one') {
    let item = {};item.formId = e.detail.formId;
    formIdlist.push(item);
  }
  return formIdlist;
}

// const getToken = () => {
//     return new Promise((resolve, reject) => {
//       let extConfig = wx.getExtConfigSync? wx.getExtConfigSync(): {}
//       let appId = extConfig.appId;
//       wx.login({
//         success: (res) => {
//           console.log("获取code1:"+res.code);
//           if (res.code) {
//             postJSON('/wxa/user/login', {
//               code: res.code,
//               appId:appId
//             }).then(data => {
//               let token = data.data.token;
//               let openId = data.data.openid;
//               wx.setStorageSync("token", token);
//               wx.setStorageSync("openId", openId);
//               resolve(data);
//             }, err => {
//               reject(err)
//             });
//           } else {
//             reject(res)
//           }
//         }
//       });
//     });
// };

function getDateOfFormatStr(time) {
  let dateArr = time.substr(0, 10).split('-');
  let hourArr = time.substr(11).split(':');
  dateArr = dateArr.map(item => parseInt(item));
  hourArr = hourArr.map(item => parseInt(item));
  return new Date(dateArr[0], dateArr[1] - 1, dateArr[2], hourArr[0], hourArr[1], hourArr[2]);
}

function formatAppointmentTime(time) {
  if (time){
    let date = new Date(time.substr(0, 10));
    let hour = time.substr(11, 5);
    return DateUtils.format('yyyy-MM-dd（周W）', date) + hour
  }else{
    return null
  }
}

function formatOrderAppointmentTime(time) {
  if (time){
    let dateArr = time.substr(0, 10).split('-');
    let hourArr = time.substr(11).split(':');
    dateArr = dateArr.map(item => parseInt(item));
    hourArr = hourArr.map(item => parseInt(item));
    let date = new Date(dateArr[0], dateArr[1] - 1, dateArr[2], hourArr[0], hourArr[1], hourArr[2]);
    let part1, part2, part3, part4;
    if (DateUtils.format('yyyy-MM-dd', date) === DateUtils.getDateByOffset()) {
      part1 = '今天';
    } else if (DateUtils.format('yyyy-MM-dd', date) === DateUtils.getDateByOffset(1)) {
      part1 = '明天';
    } else {
      part1 = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"][date.getDay()];
    }
    part2 = '（' + DateUtils.format('yyyy-MM-dd', date) + '）';
    part3 = date.getHours() > 12 ? '下午 ' : '上午 ';
    part4 = DateUtils.format('hh:mm', date);
    return part1 + part2 + part3 + part4;
  }else{
    return '时间待定'
  }
}

function preZero(val) {
  if (val < 10) {
    return '0' + val;
  }
  return val + '';
}

/**
   * 登录校验，获取openid
   * successCb 获取用户信息成功回调
**/
function login(successCb) {
  let appId = app.globalData.appId;
  wx.login({
    success: function (res) {
      let requestObj = {
        url: "/wxa/user/login",
        method: 'post',
        dataobj: {
          code: res.code,
          appId:appId
        },
      }
      wx.showLoading({
        title: '努力加载中...',
      })
      promiseRequest(requestObj).then((res) => {
        if (res.code == "200") {
          let token = res.data.token;
          let openId = res.data.openid;
          wx.setStorageSync("token", token);
          wx.setStorageSync("openId", openId);
          successCb && successCb()
        } else {
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: res.data.msg || '网络错误！',
            showCancel: false
          })
        }

      }).catch((errMsg) => {
        wx.hideLoading()
        console.log(errMsg); //错误提示信息
      });
      wx.hideLoading()
    }
  })
}

/**
   * 封装的promise
   * 参数： requestObj 请求成功回调
   * throwError: true|false  如果传true则不判断code直接执行requestObj
   */
function promiseRequest(requestObj, throwError) {
  return new Promise((resolve, reject) => {
    //网络请求
    wx.request({
      url: apiBaseUrl + requestObj.url,
      method: requestObj.method,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: requestObj.dataobj,//JSON.stringify(requestObj.dataobj)
      success: function (res) { //返回取得的数据
        let promiseQueue = app.globalData.promiseQueue;
        if (res.data.httpCode == '200' || res.data.code == '200' || throwError) {
          if (requestObj.resolve) { //如果是promise队列中的请求。
            requestObj.resolve(res.data);
            let promiseQueueItem = promiseQueue.shift();
            if (app.globalData.exeQueue) { //如果队列可执行则循环队列，保持队列只被循环一次。
               app.globalData.exeQueue = false; //防止被多次循环。
              while (promiseQueueItem) {
                promiseRequest(promiseQueueItem);
                promiseQueueItem = promiseQueue.shift();
                app.globalData.promiseQueue = promiseQueue;
              }
              if (!promiseQueueItem) {
                app.globalData.exeQueue = true;
                app.globalData.needBeginLogin = true;
              }
            }
          } else {
            resolve(res.data);
          }
        } else if (res.data.httpCode == '403' || res.data.code == '403') { //token失效重新调用login换取token
          requestObj.resolve = resolve;
          promiseQueue.push(requestObj); //请求失败了，把该请求放到promise队列，等待更新token后重新调用。
          if (!app.globalData.needBeginLogin) { //如果不需要重新登录
            return;
          }
          //防止重复调用login。
          app.globalData.needBeginLogin = false;
          login(() => { //获取完token以后执行回调
            //重新登陆以后调用一次队列中的promise；并设置队列为可循环状态。
            let promiseQueueItem = promiseQueue.shift();
            if (promiseQueueItem) {
              app.globalData.exeQueue = true;
              promiseRequest(promiseQueueItem);
              app.globalData.promiseQueue = promiseQueue;
            }
          }, true)
        } else {
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: res.data.msg
          })
        }
      },
      error: function (e) {
        wx.hideLoading()
        reject(e);
      }
    })
  });
}

/**
    * @param sx 起始点x坐标
    * @param sy 起始点y坐标
    * @param cx 控制点x坐标
    * @param cy 控制点y坐标
    * @param ex 结束点x坐标
    * @param ey 结束点y坐标
    * @param part 将起始点到控制点的线段分成的份数，数值越高，计算出的曲线越精确
    * @return 贝塞尔曲线坐标
*/
function bezier (points, part) {
  let sx = points[0]['x'];
  let sy = points[0]['y'];
  let cx = points[1]['x'];
  let cy = points[1]['y'];
  let ex = points[2]['x'];
  let ey = points[2]['y'];
  var bezier_points = [];
  // 起始点到控制点的x和y每次的增量
  var changeX1 = (cx - sx) / part;
  var changeY1 = (cy - sy) / part;
  // 控制点到结束点的x和y每次的增量
  var changeX2 = (ex - cx) / part;
  var changeY2 = (ey - cy) / part;
  //循环计算
  for (var i = 0; i <= part; i++) {
  // 计算两个动点的坐标
  var qx1 = sx + changeX1 * i;
  var qy1 = sy + changeY1 * i;
  var qx2 = cx + changeX2 * i;
  var qy2 = cy + changeY2 * i;
  // 计算得到此时的一个贝塞尔曲线上的点
  var lastX = qx1 + (qx2 - qx1) * i / part;
  var lastY = qy1 + (qy2 - qy1) * i / part;
  // 保存点坐标
  var point = {};
  point['x'] = lastX;
  point['y'] = lastY;
  bezier_points.push(point);
  }
  return {
  'bezier_points': bezier_points
  }
}
/**
 * @param {*} type 1 tab 2 navigate 3 redirect
 * @param {*} url 
 */
function go(type,url){
  if(type == 1){
    wx.switchTab({
      url: url
    })
  }else if(type == 2){
    wx.navigateTo({
      url: url
    })
  }else if(type == 3){
    wx.redirectTo({
      url: url
    })
  }
}

module.exports = {
  promiseRequest: promiseRequest,
  setWxUserInfo: setWxUserInfo,
  getWxUserInfo: getWxUserInfo,
  getOpenId: getOpenId,
  saveFormIds: saveFormIds,
  collectFormIds: collectFormIds,
  getDateOfFormatStr: getDateOfFormatStr,
  formatAppointmentTime: formatAppointmentTime,
  formatOrderAppointmentTime: formatOrderAppointmentTime,
  preZero: preZero,
  bezier:bezier,
  go:go
}
